<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
		<title>Face Recognition Attence System<</title>
    <!-- Bootstrap core CSS -->
    <link href="../css/bootstrap.min.css" rel="stylesheet">
    <!-- Custom styles for this template -->
    <link href="../css/signin.css" rel="stylesheet">
    <script type="text/javascript" src="../js/jquery-1.11.1.min.js"></script>
    <!-- Just for debugging purposes. Don't actually copy this line! -->
    <!--[if lt IE 9]><script src="assets/js/ie8-responsive-file-warning.js"></script><![endif]-->

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
	<header><img src="../images/logo.png" id="logo">Face Recognition Attence System</header>
		<div>
		<video id="video" width="320" height="320" autoplay></video>
		<canvas style="display:none" id="canvas0" width="200" height="200"></canvas><br/>
		<canvas style="display:block" id="canvas1" width="200" height="200"></canvas><br/>
		<canvas style="display:none" id="canvas2" width="200" height="200"></canvas>
		<textarea style="display:none" id="image" name="image" cols="40" rows="8"></textarea><br/>		
		</div>
	<footer>Copyright &copy; 2017 Infosys. All Rights Reserved.</footer>
  </body>
<script type="text/javascript">
var token = "";
var storage = window.localStorage;
var faceValid = false;

function run(input_file,get_data){
    /*input_file：文件按钮对象*/
    /*get_data: 转换成功后执行的方法*/
    if ( typeof(FileReader) === 'undefined' ){
        alert("抱歉，你的浏览器不支持 FileReader，不能将图片转换为Base64，请使用现代浏览器操作！");
    } else {
        try{
            /*图片转Base64 核心代码*/
            var file = input_file.files[0];
            //这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
            if(!/image\/\w+/.test(file.type)){
                alert("请确保文件为图像类型");
                return false;
            }
            var reader = new FileReader();
            reader.onload = function(){
                get_data(this.result);
            }
            reader.readAsDataURL(file);
        }catch (e){
            alert('图片转Base64出错啦！'+ e.toString())
        }
    }
}
$(function () {
   $("#imagefile").change(function () {
       run(this, function (data) {
           $('img').attr('src',data);
           var str = data.split(",")[1];             
           $('#image').val(str);
       });
   });
});

function facelogin(imgData){
	$.ajax({
		type : "post",
		url : "../loginfacade/faceLoginFacade",
		dataType : 'json',
		data : {			
			image : imgData
		},
		success : function(data, textStatus) {
			if (data.success) {
				alert(data.user.score);
				token = data.token;
				var url = data.forwardUrl;
				storage.setItem("token",token);
				window.location.href = url+"?token="+token
			}else if (!data.success){
				alert(data.errorMessage);
				window.location.href = data.forwardUrl;
			}
		},
		complete : function(XMLHttpRequest, textStatus) {
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			alert("Error:" + textStatus);
			alert(errorThrown.toString());
		}
	});
}

navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;
if (navigator.getUserMedia) {
    navigator.getUserMedia({ audio: false, video: { width: 320, height: 320 } },
            function(stream) {
                var video = document.getElementById("video");
                video.src = window.URL.createObjectURL(stream);
                video.onloadedmetadata = function(e) {
                    //console.log('nihao44eee4aaaaddda');
                    video.play();
                    autologin();
                };
            },
            function(err) {
                console.log("The following error occurred: " + err.name);
            }
    );
} else {
    console.log("getUserMedia not supported");
}
var context0 = document.getElementById("canvas0").getContext("2d");
var context1 = document.getElementById("canvas1").getContext("2d");
var context2 = document.getElementById("canvas2").getContext("2d");

var contextContent0 = document.getElementById("canvas0");
var contextContent1 = document.getElementById("canvas1");
var contextContent2 = document.getElementById("canvas2");

function picture(){
	while (detectOneValidFace(context0,contextContent0,video)==false) {
		sleep(3000);    	    	
	}
	var data0 = captureData(context0,contextContent0,video);
	sleep(3000);
	while (detectOneValidFace(context1,contextContent1,video)==false){
		sleep(3000);
	}
	var data1 = captureData(context1,contextContent1,video);
	sleep(3000);
	while (detectOneValidFace(context2,contextContent2,video)==false){
		sleep(3000);
	}
	var data2 = captureData(context2,contextContent2,video); 
	return data1;
}

function takePicture(){
	var data = picture();
	while (data.length <= 10000){
		sleep(3000);
		data = picture();
	}
	return data;
}


function captureData(context,content,video){
	context.drawImage(video, 0, 0, 200, 200);
	var imgData=content.toDataURL("image/jpeg");
    var data=imgData.substr(23);
    if (data!=undefined&&data!=null&&data!=""&&data.length>0){
    	return data;
    }else{
    	alert("Not capture any video!");
    }    
}

function detectOneValidFace(context,content,video){
	debugger;
	var imageData = captureData(context,content,video);
	$.ajax({
		method:"post",
		async: false,
		url : "../loginfacade/detectOneValidFaceFacade",
		dataType : 'json',
		data : {			
			image : imageData,
		},
		success:function(data){
		 return data.success;
		},
		complete : function(XMLHttpRequest, textStatus) {
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			alert("Error:" + textStatus);
			alert(errorThrown.toString());
		}
	});
}

function sleep(numberMillis){
    var p = new Promise(function(resolve, reject){
        //做一些异步操作

        setTimeout(function(){
            console.log('执行完成');
            resolve('随便什么数据');
        }, numberMillis);
    });
    return p;           
}

function autologin(){
	var data = 	takePicture();
	facelogin(data);
}
</script>
</html>